package com.scedu.interceptors;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Object user = request.getSession().getAttribute("user");
        log.info("preHandle={}",request.getRequestURL());

        if(user ==null) {
            log.info("检测登录失败");

            //request.setAttribute("msg","无权限请先登录");
            // 获取request返回页面到登录页
            //request.getRequestDispatcher("/login.html").forward(request,response);
            //跳转到登录页
            String url = "/login";
            response.sendRedirect(url);
            return false;
        }
        log.info("preHandle user={}",user.toString());
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion");
    }
}
